package com.gdit.zax.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gdit.zax.Constant;
import com.gdit.zax.dao.MedalDao;
import com.gdit.zax.entitys.UserMedal;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.O;
import com.gdit.zax.utils.TextUtil;
import com.gdit.zax.utils.VeriFicUtil;

public class ListMedal extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String accesstoken = request.getParameter("accesstoken");
		int uid = TextUtil.String2int(request.getParameter("uid"), -1);
		int page = TextUtil.String2int(request.getParameter("page"), 1);
		
		//检测参数
		if (TextUtil.isEmpty(accesstoken) && uid==-1) {
			O.printFail(response, 1, "accesstoken、uid必须填写一项!");
			return;
		}
		
		
		//检测连接、用户
		if (uid==-1) {
			uid = VeriFicUtil.getVFID(accesstoken);
		}
		
		if (uid==Integer.MIN_VALUE || uid==Integer.MAX_VALUE) {
			O.printNoLogin(response);
			return;
		}
		
		Connection conn = DBUtil.getConnection();
		if (conn==null) {
			O.printFail(response, 1000, "数据库连接失败!");
			return;
		}
		
		
		DAOFactory dao  = DAOFactory.init(conn, request, response);
		MedalDao mdao = dao.getMedalDao();
		ArrayList<UserMedal> list = mdao.listUserMedal(uid, page, 1000);
		ArrayList<HashMap<String, Object>> list2=new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < list.size(); i++) {
			UserMedal um = list.get(i);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("id", um.getT_medal_id());
			map.put("content", um.getT_medal_content());
			map.put("name", um.getT_medal_name());
			map.put("pic", Constant.WEBRoot + um.getT_medal_pic());
			list2.add(map);
		}
		O.printSuccess(response,list2);
	}

}
